package com.lagou.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

public class ClientHandler extends SimpleChannelInboundHandler<RpcResponse> implements Callable {
    private ChannelHandlerContext ctx;
    private RpcResponse rpcResponse;
    private RpcRequest rpcRequest;
    private String para;
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端与服务端建立连接..");
        this.ctx=ctx;
    }

    @Override
    protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse) throws Exception {
        System.out.println("服务器返回数据..."+rpcResponse);
        this.rpcResponse=rpcResponse;
        notify();
    }
    //被代理对象调用，发送数据给服务器，等待被唤醒wait
    @Override
    public synchronized Object call() throws Exception {
        System.out.println("call 方法执行..");
        ctx.writeAndFlush(rpcRequest);
        wait();
        return rpcResponse.getData();
    }

    public void setRpcRequest(RpcRequest rpcRequest) {
        this.rpcRequest = rpcRequest;
    }

    public String getPara() {
        return para;
    }

    public void setPara(String para) {
        this.para = para;
    }
}
